package com.onlyphoto.onlymall.mvp.view.activity

import android.content.Intent
import android.net.Uri
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.lcw.library.imagepicker.ImagePicker
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.api.Urls
import com.onlyphoto.onlymall.base.BaseActivity
import com.onlyphoto.onlymall.bean.FileBean
import com.onlyphoto.onlymall.bean.SelectPicBean
import com.onlyphoto.onlymall.events.UploadPicEvent
import com.onlyphoto.onlymall.interfaces.ProgressListener
import com.onlyphoto.onlymall.mvp.contract.CUploadPic
import com.onlyphoto.onlymall.mvp.presenter.PUploadPicImpl
import com.onlyphoto.onlymall.mvp.view.binder.PicBinder
import com.onlyphoto.onlymall.utils.ConfigUtil
import com.onlyphoto.onlymall.utils.FileUtil
import com.onlyphoto.onlymall.utils.GlideLoader
import com.onlyphoto.onlymall.widget.AlertDialog
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.activity_uploadpic.*

import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.Exception
import kotlin.math.max


class UploadPicActivity : BaseActivity<PUploadPicImpl>(), CUploadPic.IVUploadPic, ProgressListener {

    var layoutManager: GridLayoutManager? = null
    var items: Items? = null
    var adapter: MultiTypeAdapter? = null
    var myDisposable = CompositeDisposable()
    var picItem: SelectPicBean? = null
    private var selectPicBean: SelectPicBean? = null

    //上传的图片个数
    private var uploadCount = 0
    private var isChange = false
    var maxUploadSize = 0
    var maxSelectSize = 0

    var orderId = ""
    var goodsId = 0

    var uploadedList: ArrayList<String>? = null

    companion object {
        const val ALBUM_RESULT_CODE = 300
    }

    override fun retry() {}

    override fun init() {
        orderId = intent.getStringExtra("orderId")!!
        goodsId = intent.getIntExtra("goodsId", 0)
        maxUploadSize = intent.getIntExtra("numLimit", 0)
        uploadedList = intent.getStringArrayListExtra("picList")

        if (maxUploadSize == uploadedList?.size) {
            upload.visibility = View.GONE
        }
        maxSelectSize = maxUploadSize

        initRv()
    }

    private fun initRv(){
        layoutManager = GridLayoutManager(this, 4)
        items = Items()
        adapter = MultiTypeAdapter(items!!)
        val binder = PicBinder()
        binder.setOnItemClickEvent(object :PicBinder.OnItemClickEvent{
            override fun itemClick(bean: SelectPicBean, pos: Int) {
                selectPicBean = bean
                if (selectPicBean!!.type == SelectPicBean.Type_Add) {
                    if (items!!.size - 1 == maxUploadSize) {
                        AlertDialog(this@UploadPicActivity).builder()
                                .setCancelable(false)
                                .setMsg("已达到图片个数上限")
                                .setPositiveButton("我知道了") { }.show()
                        return
                    } else {
                        maxSelectSize -= items!!.size - 1
                        openAlbum()
                    }
                } else {
                    //展示大图
                    /*val intent = Intent(this@UploadPicActivity, ImageDetailActivity::class.java)
                    intent.putExtra("position", pos.toString() + "")
                    val list = ArrayList<String>()
                    list.add(selectPicBean?.url!!)
                    if (list.size > 0) {
                        intent.putStringArrayListExtra("urls", list)
                        startActivity(intent)
                    }*/
                }
            }
        })
        binder.setDeleteSelectPicListener(object :PicBinder.DeleteSelectPicListener{
            override fun delete(position: Int) {
                AlertDialog(this@UploadPicActivity).builder()
                        .setMsg("是否要删除？")
                        .setPositiveBold().setPositiveButton("删除") {
                            items?.removeAt(position)
                            adapter?.notifyDataSetChanged()
                        }.setNegativeButton("取消") { }.show()
            }

        })
        adapter?.register(SelectPicBean::class.java, binder)
        rv_pic.layoutManager = layoutManager
        rv_pic.adapter = adapter
    }

    private fun openAlbum() {
        ImagePicker.getInstance()
                .setTitle("选择照片")                        //设置标题
                .showCamera(true)               //设置是否显示拍照按钮
                .showImage(true)                 //设置是否展示图片
                .showVideo(false)                //设置是否展示视频
                .setSingleType(true)                       //设置图片视频不能同时选择
                .setMaxCount(maxSelectSize)                            //设置最大选择图片数目(默认为1，单选)
                .setImageLoader(GlideLoader())             //设置自定义图片加载器
                .start(this, ALBUM_RESULT_CODE)     //ALBUM_RESULT_CODE为Intent调用的requestCode
    }

    override fun initListener() {
        //点击事件初始化
        back.setOnClickListener{
            if (!showBackDialog()) {
                finish()
            }
        }
        upload.setOnClickListener {
            uploadCount = 0
            upLoadPic(0)
        }
    }

    private fun upLoadPic(type: Int) {
        var flag = false
        val url = ConfigUtil.instance.getUrl(Urls.CUSTOM_IMG)
        for (i in items!!.indices) {
            picItem = items!![i] as SelectPicBean?
            if (picItem == null || picItem!!.url == null) {
                continue
            }
            if (picItem!!.type == SelectPicBean.Type_None || picItem!!.type == SelectPicBean.Type_UploadFailed) {
                flag = true
                val bean = FileBean()
                bean.uploadKey = "file"
                //bean.addExtraParams("type", "")
                bean.addExtraParams("order_id", orderId)
                bean.addExtraParams("goods_id", goodsId.toString())
                bean.pos = i
                val uri = Uri.parse(picItem!!.url)
                bean.fileSrc = uri.path
                try {
                    uploadCount++
                    picItem!!.uiProgressListener.onProgress(50, 100, false)
                    FileUtil.upLoadFile(url, bean, this, myDisposable)
                } catch (e: Exception) {
                    e.printStackTrace()
                }

                break
            }
        }
        if (!flag && type == 0) {
            showToast("无新增图片")
            return
        }
    }

    override fun onProgress(currentBytes: Long, contentLength: Long, done: Boolean) {
        picItem!!.uiProgressListener.onProgress(currentBytes, contentLength, done)
    }

    override fun onSuccess(msg: String?) {
        upLoadPic(1)
        picItem!!.uiProgressListener.onSuccess(msg)
    }

    override fun onFailed(exception: Exception?) {
        picItem!!.uiProgressListener.onFailed(exception)
    }


    override fun loadData() {
        //加载数据
        if (uploadedList != null && uploadedList!!.size > 0) {
            for (str in uploadedList!!) {
                val bean =  SelectPicBean()
                bean.url = str
                bean.type = SelectPicBean.Type_Uploaded
                items?.add(bean)
            }
        }
        if (uploadedList == null || uploadedList!!.size < maxUploadSize) {
            val bean = SelectPicBean()
            bean.type = SelectPicBean.Type_Add
            items?.add(bean)
        }
        adapter?.notifyDataSetChanged()
    }

    override fun isFullScreen(): Boolean {
        //是否沉浸式， 默认非沉浸式
        return false
    }

    public override fun initCustomerStatusManager() {

    }

    override fun setContentViewId(): Int {
        return R.layout.activity_uploadpic
    }

    override fun onBackPressed() {
         if (!showBackDialog()) {
             super.onBackPressed()
         }
    }

    private fun showBackDialog(): Boolean{
        if (isChange || uploadCount > 0) {
            AlertDialog(this).builder().setCancelable(false).setMsg("有图片未上传,是否继续返回?")
                    .setPositiveBold().setPositiveButton("取消") { }.setNegativeButton("确定") { finish() }.show()
            return true
        }
        return false
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            ALBUM_RESULT_CODE -> {
                val imagePaths = data?.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES)
                if (imagePaths != null && imagePaths.size > 0) {
                    for (path in imagePaths) {
                        val bean =  SelectPicBean()
                        bean.url = path
                        items?.add(adapter!!.itemCount - 1, bean)
                    }
                    isChange = true
                }
                adapter?.notifyDataSetChanged()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: UploadPicEvent) {
        synchronized(this) {

            val pos = event.pos
            if (event.type == UploadPicEvent.UPLOAD_FAILED) {
                showToast(event.message!!)
                (items!![pos] as SelectPicBean).type = SelectPicBean.Type_UploadFailed
                adapter!!.notifyDataSetChanged()
            } else {
                uploadCount--
                (items!![pos] as SelectPicBean).type = SelectPicBean.Type_Uploaded
                adapter!!.notifyDataSetChanged()
            }
            if (uploadCount == 0) {
                isChange = false
                if (items!!.size - 1 == maxUploadSize) {
                    upload.isEnabled = false
                    items?.removeAt(items!!.lastIndex)
                }
            }
        }


    }

    override fun onDestroy() {
        super.onDestroy()
        FileUtil.dispose()
    }

    override fun createPresenter() {
        mPresenter = PUploadPicImpl(mContext, this)
    }

    override fun showLoading() {

    }

    override fun hideLoading() {

    }

}
